//
//  AccountUserinfoVC.m
//  ImGuider
//
//  Created by llt on 2017/5/12.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "AccountUserinfoVC.h"
#import "AccountCell.h"

#import "ChoosePhotoVC.h"

#import "ChageUserInfoVC.h"

@interface AccountUserinfoVC () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (nonatomic, strong) NSArray *dataSource;


@end

@implementation AccountUserinfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self reloadTB];
}

- (void)setup {
    
    self.title = MYLocalizedString(@"MYINFO_TITLE", nil);
    self.tableView.tableFooterView = [UIView new];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.headImageView.layer.borderWidth = 1.0f;
    self.headImageView.layer.borderColor = kBGColor.CGColor;
    
    [self reloadTB];
}

- (void)reloadTB {
    NSString *username = [UserManager sharedManager].user.username;
    
    NSString *realname = [UserManager sharedManager].user.realname;
    NSString *email = [UserManager sharedManager].user.email;
    
    if (username.length > 0) {
        
        self.dataSource = @[@{@"name":MYLocalizedString(@"MYINFO_USERNAME", nil),@"account":realname ? realname : @""},
                            @{@"name":MYLocalizedString(@"MYINFO_CHANGE_NUMBER", nil),@"account":username},
                            @{@"name":MYLocalizedString(@"MYINFO_EMAIL", nil),@"account":email ? email : @""},
                            @{@"name":MYLocalizedString(@"MYINFO_CHANGE_PSW", nil),@"account":@"******"}];
    } else {
        
        self.dataSource = @[@{@"name":MYLocalizedString(@"MYINFO_USERNAME", nil),@"account":realname ? realname : @""},
                            @{@"name":MYLocalizedString(@"MYINFO_LINK_NUMBER", nil),@"account":@""},
                            @{@"name":MYLocalizedString(@"MYINFO_EMAIL", nil),@"account":email ? email : @""}];
    }
    
    
    [self.headImageView setImageURL:[NSURL URLWithString:[UserManager sharedManager].user.headimg] placeholderImage:[UIImage imageNamed:@"default"]];
    [self.tableView reloadData];
}
- (IBAction)changeHeadAction:(id)sender {
    
    ChoosePhotoVC *photoVC = [[ChoosePhotoVC alloc] init];
    photoVC.maxCount = 1;
    photoVC.allowsEditing = YES;
    [photoVC showWithViewController:self selectArrayBlock:^(NSArray *photoArray) {
        
        UIImage *image = [photoArray firstObject];
        
        if (!image || ![image isKindOfClass:[UIImage class]]) {
            
            [IGUtil showToast:@"请选择正确的图片"];
            return;
        }
        
        [NetAPIManager updateUserinfo:image type:@"headimg" block:^(NSString *result, NSError *error) {
            
            if (!error) {
                [IGUtil showToast:MYLocalizedString(@"PUBLIC_MODIFY_SUCCESS", nil)];
                [self reloadTB];
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
            } else {
                
                [IGUtil showToast:[IGUtil tipFromError:error]];
            }
        }];
    }];
}


#pragma mark -UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dict = self.dataSource[indexPath.row];
    
    AccountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell configWithDict:dict];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {// 修改用户名
        
        [self changeUserName];
        
        return;
    }
    
    if (indexPath.row == 2) {// 修改邮箱
        
        [self changeEmail];
        
        return;
    }
    
    //0绑定手机号；1更换手机号;2修改密码
    NSInteger type = 0;
    
    if (indexPath.row == 1 && [UserManager sharedManager].user.username > 0) {
        
        type = 1;
        
    } else if (indexPath.row == 3) {
        
        type = 2;
    }
    
    ChageUserInfoVC *changeVC = [ChageUserInfoVC new];
    changeVC.type = type;
    [self.navigationController pushViewController:changeVC animated:YES];
}


- (void)changeUserName {
    
    UIAlertController *changeUseNameAlert = [UIAlertController alertControllerWithTitle:nil message:MYLocalizedString(@"MYINFO_CHNAGENICK", nil) preferredStyle:UIAlertControllerStyleAlert];
    [changeUseNameAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = MYLocalizedString(@"MYINFO_INPUTNICK", nil);
        textField.text = [UserManager sharedManager].user.realname;
        textField.returnKeyType = UIReturnKeyDone;//Done按钮
        [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }];
    
    [changeUseNameAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) style:UIAlertActionStyleCancel handler:nil]];
    [changeUseNameAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CONFIRM", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UITextField *userNameTF = changeUseNameAlert.textFields.firstObject;
        if ([IGUtil isStringLenght0:userNameTF.text]) {
            [IGUtil showToast:MYLocalizedString(@"MYINFO_INPUTNICK", nil)];
            return;
        }
        [NetAPIManager updateUserinfo:userNameTF.text type:@"realname" block:^(NSString *result, NSError *error) {
            
            if (!error) {
                [IGUtil showToast:result];
                [self reloadTB];
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
            }
        }];
    }]];
    
    [self presentViewController:changeUseNameAlert animated:YES completion:nil];
}

- (void)changeEmail {
    
    UIAlertController *changeUseNameAlert = [UIAlertController alertControllerWithTitle:nil message:MYLocalizedString(@"MYINFO_EMAIL", nil) preferredStyle:UIAlertControllerStyleAlert];
    [changeUseNameAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = MYLocalizedString(@"MYINFO_EMAIL", nil);
        textField.returnKeyType = UIReturnKeyDone;//Done按钮
        [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }];
    
    [changeUseNameAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) style:UIAlertActionStyleCancel handler:nil]];
    [changeUseNameAlert addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CONFIRM", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UITextField *userNameTF = changeUseNameAlert.textFields.firstObject;
        if (![self validateEmail:userNameTF.text]) {
            [IGUtil showToast:MYLocalizedString(@"MYINFO_EMAIL", nil)];
            
            return;
        }
        [NetAPIManager updateUserinfo:userNameTF.text type:@"email" block:^(NSString *result, NSError *error) {
            
            if (!error) {
                [IGUtil showToast:result];
                [self reloadTB];
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
            }
        }];
    }]];
    
    [self presentViewController:changeUseNameAlert animated:YES completion:nil];
}

- (BOOL)validateEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}

#define MAX_STARWORDS_LENGTH 100

-(void)textFieldDidChange:(UITextField *)textField {
    
    NSString *toBeString = textField.text;
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (position) {
        
        return;
    }
    
    if (toBeString.length > MAX_STARWORDS_LENGTH) {
        
        NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
        if (rangeIndex.length == 1) {
            
            textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
        } else  {
            
            NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
            textField.text = [toBeString substringWithRange:rangeRange];
        }
    }
}

@end

